import { useBearStore } from '@/store/BearStore'
import { useFoodStore } from '@/store/FoodStore'
import { useEffect } from 'react'
import { useState } from 'react'
import { shallow } from 'zustand/shallow'

export const BearBox = () => {
  const bears = useBearStore(state => state.bears)
  const increasePopulation = useBearStore(state => state.increasePopulation)
  const removeAllBears = useBearStore(state => state.removeAllBears)

  const [bgColor, setBgColor] = useState(
    useFoodStore.getState().fish > 2 ? 'lightgreen' : 'lightblue'
  )

  useEffect(() => {
    // const unsub = useFoodStore.subscribe(state => {
    //   if (state.fish > 2) {
    //     setBgColor('lightgreen')
    //   } else {
    //     setBgColor('lightblue')
    //   }
    // })

    const unsub = useFoodStore.subscribe(
      state => state.fish,
      (fish, prevFish) => {
        if (fish > 2 && prevFish >= 2) {
          setBgColor('lightgreen')
        } else {
          setBgColor('lightblue')
        }
      },
      {
        fireImmediately: true,
        equalityFn: shallow
      }
    )
    return unsub
  }, [])

  return (
    <div
      style={{
        backgroundColor: bgColor
      }}
      className="box"
    >
      <h1>BearBox</h1>
      <div>{bears}</div>
      <p>{Math.random()}</p>
      <button onClick={increasePopulation}>add bear</button>
      <button onClick={removeAllBears}>remove bear</button>
    </div>
  )
}
